package com.hymane.materialhome.api.presenter.impl;

import android.os.AsyncTask;
import android.util.Base64;

import com.google.protobuf.ByteString;
import com.hymane.materialhome.BaseApplication;
import com.hymane.materialhome.MaterialMessage;
import com.hymane.materialhome.R;
import com.hymane.materialhome.api.ApiCompleteListener;
import com.hymane.materialhome.api.model.IBookListModel;
import com.hymane.materialhome.api.model.impl.BookListModelImpl;
import com.hymane.materialhome.api.presenter.IBookListPresenter;
import com.hymane.materialhome.api.view.IBookListView;
import com.hymane.materialhome.bean.http.douban.BaseResponse;
import com.hymane.materialhome.bean.http.douban.BookInfoResponse;
import com.hymane.materialhome.bean.http.douban.BookListResponse;
import com.hymane.materialhome.utils.HttpUtil;
import com.hymane.materialhome.utils.Utils;
import com.hymane.materialhome.utils.common.NetworkUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;


/**
 * Author   :hymanme
 * Email    :hymanme@163.com
 * Create at 2016/8/5
 * Description:
 */
public class BookListPresenterImpl implements IBookListPresenter, ApiCompleteListener {
    private IBookListView mBookListView;
    private IBookListModel mBookListModel;

    public BookListPresenterImpl(IBookListView view) {
        mBookListView = view;
        mBookListModel = new BookListModelImpl();
    }

    /**
     * 加载数据
     */
    @Override
    public void loadBooks(String q, String tag, int start, int count, String fields) {
        if (!NetworkUtils.isConnected(BaseApplication.getApplication())) {
            mBookListView.showMessage(BaseApplication.getApplication().getString(R.string.poor_network));
            mBookListView.hideProgress();
//            return;
        }
        mBookListView.showProgress();
        mBookListModel.loadBookList(q, tag, start, count, fields, this);
    }

    @Override
    public void cancelLoading() {
        mBookListModel.cancelLoading();
    }

    /**
     * 访问接口成功
     *
     * @param result 返回结果
     */
    @Override
    public void onComplected(Object result) {
        if (result instanceof BookListResponse) {
            int index = ((BookListResponse) result).getStart();
            if (index == 0) {
                mBookListView.refreshData(result);
            } else {
                mBookListView.addData(result);
            }
            mBookListView.hideProgress();

            // save to db
            for (BookInfoResponse bookInfoResponse : ((BookListResponse) result).getBooks())
            {
                try {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
                    objectOutputStream.writeObject(bookInfoResponse);

                    byte[] _byArr= byteArrayOutputStream.toByteArray();

//                    Utils.getFile(BaseApplication.getApplication(), _byArr, "", "booklist");

                    //  字节数组到字符串的转换：
//                    String _strText= Base64.encodeToString(_byArr.toByteArray(),Base64.DEFAULT);
                    ///////byte[] _byArr= _byteArrayOutputStream.toByteArray(）

//                    String params[] = {new String(_byArr, "UTF-8")};
                    byte[] params[] = {_byArr};
                    new SaveBookListTask().execute(params);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }

    /**
     * 请求失败
     *
     * @param msg 错误信息
     */
    @Override
    public void onFailed(BaseResponse msg) {
        mBookListView.hideProgress();
        if (msg == null) {
            return;
        }
        mBookListView.showMessage(msg.getMsg());
    }


    private class SaveBookListTask extends AsyncTask<byte[], Integer, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
//            textView.setText("loading...");
        }

        //doInBackground方法内部执行后台任务,不可在此方法内修改UI
        @Override
        protected String doInBackground(byte[]... params) {
            for (byte[] bookInfoString : params)
            {
                Utils.getFile(BaseApplication.getApplication(), bookInfoString, "", "booklist");

                MaterialMessage.TransPackage.Builder transPackage = MaterialMessage.TransPackage.newBuilder();
                transPackage.setId(MaterialMessage.TransPackage.PackageId.SaveBookList);
                transPackage.setPackage(ByteString.copyFrom(bookInfoString));


                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                try {
                    transPackage.build().writeTo(byteArrayOutputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                String url = null;
                try {

                    byte[] buffer = byteArrayOutputStream.toByteArray();
                    Utils.getFile(BaseApplication.getApplication(), buffer, "", "buffer");

                    MaterialMessage.TransPackage transPackage_ = MaterialMessage.TransPackage.parseFrom(buffer);

                    byte[] book = transPackage_.getPackage().toByteArray();

                    HttpUtil.sendPostRequest(HttpUtil.BASE_URL + "BookListServlet", buffer);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                String result = HttpUtil.queryStringForPost(url);
            }
            return new String("0");
        }

        //onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(String result) {

        }
    }
}
